﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using AFS.Visitation.Addin.Entities;
using AFS.Visitation.Addin.Properties;
using Microsoft.Office.Interop.Outlook;
using DictionaryUtility = AFS.Visitation.Addin.Dictionary.DictionaryFactory;
using Utility = AFS.Visitation.Addin.Common.Utility;
using XMLVariables = AFS.Visitation.Addin.XML;

namespace AFS.Visitation.Addin.XML
{
    public class InfoPathFormWriter
    {

        private static string nameSpace = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-06-06T16:00:10";
        //private static string myFieldsNameSpace = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns:pc=\"http://schemas.microsoft.com/office/infopath/2007/PartnerControls\" xmlns:dfs=\"http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\" xmlns:ma=\"http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes\" xmlns:d=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\" xmlns:q=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields\" xmlns:dms=\"http://schemas.microsoft.com/office/2009/documentManagement/types\" xmlns:my=\"http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-06-06T16:00:10\" xmlns:xd=\"http://schemas.microsoft.com/office/infopath/2003\" xmlns:xdServerInfo=\"http://schemas.microsoft.com/office/infopath/2009/xslt/ServerInfo\" xmlns:xsf3=\"http://schemas.microsoft.com/office/infopath/2009/solutionDefinition/extensions\" xml:lang=\"en-US\"";
        private static string pcNameSpace = "http://schemas.microsoft.com/office/infopath/2007/PartnerControls";

        private static Dictionary<string, string> appointmentDetailsDictionary;
        private static Dictionary<string, string> attachmentsBase64Dictionary;
        private static Dictionary<string, List<MeetingRecipient>> meetingRecipientsDictionary;
        private static MeetingOrganizer meetingOrganizer;

        private static List<string> visitLocationsList;
        private static List<string> afsLocationssList;
        private static Settings settings = new Settings();

        private static void InsertSingleElementIntoXMLTextWriter(XmlTextWriter xmlTextWriter, string targetNode)
        {
            xmlTextWriter.WriteStartElement("my", targetNode, nameSpace);

            // Looking up appointment detail record via targetNode being passed, which serves as key in this instance.
            if (appointmentDetailsDictionary.ContainsKey(targetNode))
            {
                xmlTextWriter.WriteString(appointmentDetailsDictionary[targetNode]);
            }

            xmlTextWriter.WriteEndElement();
        }

        private static void InsertSingleElementIntoXMLTextWriter(XmlTextWriter xmlTextWriter, string targetNode, string nodeValue, string prefix, string ns)
        {
            xmlTextWriter.WriteStartElement(prefix, targetNode, ns);
            xmlTextWriter.WriteString(nodeValue);
            xmlTextWriter.WriteEndElement();
        }

        private static void InsertBase64AttachmentsIntoXMLTextWriter(XmlTextWriter xmlTextWriter, string targetNode)
        {
            foreach (string key in attachmentsBase64Dictionary.Keys)
            {
                xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeGroupFileUploadTable, nameSpace);
                xmlTextWriter.WriteStartElement("my", targetNode, nameSpace);
                xmlTextWriter.WriteString(attachmentsBase64Dictionary[key]);
                xmlTextWriter.WriteEndElement();
                xmlTextWriter.WriteEndElement();
            }
        }

        // TODO: Why do we need a dictionary for MeetingOrganizer if there's only 1 organizer per meeting?
        // Got rid of dictionary. Now need to verify that there's nothing I'm overlooking
        private static void InsertSinglePeopleFieldIntoXMLTextWriter(XmlTextWriter xmlTextWriter, string targetNode)
        {
            xmlTextWriter.WriteStartElement("my", targetNode, nameSpace);
            xmlTextWriter.WriteStartElement("pc", ElementNames.XmlNodePerson, pcNameSpace);

            if (meetingOrganizer != null)
            {
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDisplayName, meetingOrganizer.DisplayName, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountID, meetingOrganizer.AccountID, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountType, meetingOrganizer.AccountType.ToString(), "pc", pcNameSpace);
            }
            else
            {
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDisplayName, String.Empty, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountID, String.Empty, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountType, String.Empty, "pc", pcNameSpace);
            }

            //if (meetingOrganizersDictionary.ContainsKey(targetNode))
            //{
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeDisplayName, meetingOrganizersDictionary[targetNode].DisplayName, "pc", pcNameSpace);
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeAccountID, meetingOrganizersDictionary[targetNode].AccountID, "pc", pcNameSpace);
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeAccountType, meetingOrganizersDictionary[targetNode].AccountType, "pc", pcNameSpace);
            //}
            //else
            //{
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeDisplayName, String.Empty, "pc", pcNameSpace);
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeAccountID, String.Empty, "pc", pcNameSpace);
            //    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, XMLVariables.XmlNodeAccountType, String.Empty, "pc", pcNameSpace);

            //}
            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();
        }

        private static void InsertRecipientsValuesIntoXMLTextWriter(XmlTextWriter xmlTextWriter, string targetNode)
        {
            xmlTextWriter.WriteStartElement("my", targetNode, nameSpace);

            if (meetingRecipientsDictionary.ContainsKey(targetNode))
            {
                // TODO: Implement INumerable interface. No enumerator for Person Abstract
                foreach (MeetingRecipient person in meetingRecipientsDictionary[targetNode])
                {
                    xmlTextWriter.WriteStartElement("pc", ElementNames.XmlNodePerson, pcNameSpace);
                    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDisplayName, person.DisplayName, "pc", pcNameSpace);
                    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountID, person.AccountID, "pc", pcNameSpace);
                    InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountType, person.AccountType.ToString(), "pc", pcNameSpace);
                    xmlTextWriter.WriteEndElement();
                }
            }

            else
            {
                xmlTextWriter.WriteStartElement("pc", ElementNames.XmlNodePerson, pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDisplayName, String.Empty, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountID, String.Empty, "pc", pcNameSpace);
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAccountType, String.Empty, "pc", pcNameSpace);
                xmlTextWriter.WriteEndElement();
            }

            xmlTextWriter.WriteEndElement();
        }

        // TODO: This seems like it should be called InsertNonAFSRecipients.  What's being validated here? We're just concatenating email addresses.
        // Seems like just using sourceNode value as key.
        private static void InsertRecipientsValidationField(XmlTextWriter xmlTextWriter, string sourceNode, string targetNode)
        {
            xmlTextWriter.WriteStartElement("my", targetNode, nameSpace);

            if (meetingRecipientsDictionary.ContainsKey(sourceNode))
            {
                StringBuilder emailAddresses = new StringBuilder();


                foreach (MeetingRecipient meetingRecipient in meetingRecipientsDictionary[targetNode])
                {
                    emailAddresses.AppendFormat("{0};", meetingRecipient.AccountID);
                }

                xmlTextWriter.WriteString(emailAddresses.ToString());
                // xmlTextWriter.WriteString(meetingRecipientsDictionary[sourceNode].nonAFSPersonDetails.ToString());
            }
            else
            {
                xmlTextWriter.WriteString(String.Empty);
            }

            xmlTextWriter.WriteEndElement();
        }

        //private static void InsertVisitLocationFields(XmlTextWriter xmlTextWriter)
        //{
        //    foreach (string location in visitLocationsList)
        //    {
        //        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeInPersonOfficeVisitLocation, location, "my", nameSpace);
        //    }
        //}

        private static void InsertLisboxFields(XmlTextWriter xmlTextWriter, List<string> list, string node)
        {
            foreach (string item in list)
            {
                InsertSingleElementIntoXMLTextWriter(xmlTextWriter, node, item, "my", nameSpace);
            }
        }

        // Need to make this more dynamic in the case of InfoPath Form changes.
        // "Schema" is currently hard coded.
        // Passing AppointmentItem because there is already one created in caller method RibbonCreateVisitationRequest(), why create another instance when we already have on stack?
        public static byte[] CreateForm(RequestDetailsFormRegion requestDetails, AppointmentItem appointmentItem)
        {
            // meetingOrganizersDictionary = DictionaryFactory.GetMeetingOrganizerDictionary(appointmentItem); 
            appointmentDetailsDictionary = DictionaryUtility.GetAppointmentDetailsDictionary(requestDetails, appointmentItem);
            attachmentsBase64Dictionary = DictionaryUtility.GetAttachmentsBase64Dictionary(appointmentItem);
            meetingRecipientsDictionary = DictionaryUtility.GetRecipientsDictionary(appointmentItem);
            visitLocationsList = Utility.GetListboxValues(requestDetails.lstVisitLocations);
            //visitLocationsList = Utility.GetVisitLocationsList(formRegions.RequestDetailsFormRegion);
            afsLocationssList = Utility.GetListboxValues(requestDetails.lstAFSOffices);

            if (appointmentItem.GetOrganizer() != null)
                meetingOrganizer = new MeetingOrganizer(appointmentItem.Session.CurrentUser);

            byte[] infoPathFormData = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
                {
                    try
                    {
                        xmlTextWriter.WriteStartDocument();

                        xmlTextWriter.WriteProcessingInstruction("mso-infoPathSolution",
                        "name=\"urn:schemas-microsoft-com:office:infopath:AFS-Visitation-Form-Library:-myXSD-2012-06-06T16-00-10\" solutionVersion=\"1.0.0.936\" productVersion=\"14.0.0.0\" PIVersion=\"1.0.0.0\" href=\"" +
                        settings.FormLibraryPath + "Forms/template.xsn\""); //href=\"https://tssusa.accenture.com/sites/afs_visitation_tool_test/AFS%20Visitation%20Form%20Library/Forms/template.xsn\"");

                        xmlTextWriter.WriteProcessingInstruction("mso-Application", "progid=\"InfoPath.Document\" versionProgid=\"InfoPath.Document.3\"");
                        xmlTextWriter.WriteProcessingInstruction("mso-infoPath-file-attachment-present", String.Empty);

                        xmlTextWriter.WriteStartElement("my", "myFields", nameSpace);
                        xmlTextWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                        xmlTextWriter.WriteAttributeString("xmlns", "pc", null, "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");

                        #region Common Section
                        xmlTextWriter.WriteStartElement("my", "Common", nameSpace);

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitStartDate);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitDuration);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitTitle);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitEndDate);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitType);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRenewExistingOrExpiredRequest);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodePreviousVisitRequestID);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRequestOnBehalfOfSomeoneElse);

                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeInPersonVisitLocations, nameSpace);

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeInPersonOfficeVisitLocation);

                        //InsertVisitLocationFields(xmlTextWriter);
                        InsertLisboxFields(xmlTextWriter, visitLocationsList, ElementNames.XmlNodeInPersonOfficeVisitLocation.ToString());
                        InsertLisboxFields(xmlTextWriter, afsLocationssList, ElementNames.XmlNodeAFSOfficeLocations.ToString());

                        xmlTextWriter.WriteEndElement();
                        // TODO: Keep an eye on these calls.
                        InsertSinglePeopleFieldIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSubmittedOnBehalfOf);

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodevalidateSubmittedOnBehalfOfEmailId);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodePreviousIDSection);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSectionSubmittedOnBehalfOf);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRequestInitiation);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSubmitterId);

                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeInPersonVisitLocationForStaffing, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingLocation);
                        xmlTextWriter.WriteEndElement();

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRecurringReasonForVisit);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeReasonForVisitHelpText);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeFrequencyOfVisit);

                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeAFSLocationSupplementaryQuestions, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeForeignNational);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAFSOfficeLocations);

                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeCommonForeignNationalGroup, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeForeignNationalName);
                        xmlTextWriter.WriteEndElement();

                        xmlTextWriter.WriteEndElement();

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAFSLocationSupplementaryQuestionsHelpText);

                        xmlTextWriter.WriteEndElement();
                        #endregion

                        #region OneTime Recurring
                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeOneTimeRecurring, nameSpace);

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDoesMeetingIncludeAgenda);

                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeGroupFileUpload, nameSpace);

                        InsertBase64AttachmentsIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRecurringFileUpload);

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRecurringFileUploadSection);
                        xmlTextWriter.WriteEndElement();

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeImpactIfRejected);
                        // TODO: Keep an eye on these calls.
                        InsertRecipientsValidationField(xmlTextWriter, ElementNames.XmlNodeAFSPersonnelInvolved, ElementNames.XmlNodeValidateACNPersonnel);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeValidateAFSPersonnel);
                        InsertRecipientsValuesIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeAFSPersonnelInvolved);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSendEmailToAFSPersonnelInvolved);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDoesVisitIncludeAgendaOrMaterials);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeRecurringMoreThanEightPersonnel);

                        xmlTextWriter.WriteEndElement();

                        #endregion

                        #region Staffing
                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeStaffing, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingRoleDescription);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingClientName);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingProjectName);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingResourceLevel);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingRoleName);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingRoleType);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingRoleTypeOther);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingHoursPerWeek);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingOtherLeaderShipRoles);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingValidateResourceName);

                        InsertSinglePeopleFieldIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingResourceName);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeStaffingACNResourceName);

                        xmlTextWriter.WriteEndElement();
                        #endregion

                        #region Social
                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeSocial, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSocialConfirmBusinessHasTakenPlace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSocialVisitBusinessTakePlaceExplanation);
                        InsertSinglePeopleFieldIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSocialACNPersonnelInvolved);
                        InsertRecipientsValuesIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSocialAFSPersonnelInvolved);
                        InsertRecipientsValidationField(xmlTextWriter, ElementNames.XmlNodeSocialAFSPersonnelInvolved, ElementNames.XmlNodeSocialValidateACNPersonnel);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSocialValidateAFSPersonnel);
                        xmlTextWriter.WriteEndElement();
                        #endregion

                        #region ApproverSection
                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeApproversSection, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeOutsideManagerAppproval);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeVisitTypeDeterminedByFSO);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeInitialFSOComments);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeInitialFSOApproval);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeOutsideManagerComments);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDSSApproval);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeDSSComments);
                        xmlTextWriter.WriteEndElement();
                        #endregion

                        #region FinalStatusSection
                        xmlTextWriter.WriteStartElement("my", ElementNames.XmlNodeFinalStatusSection, nameSpace);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeFinalStatus);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeFinalApprovalDate);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeFinalComments);
                        xmlTextWriter.WriteEndElement();
                        #endregion

                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeFilename);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeBackEndVisitType);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeSectionSubmitButton);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeIsReadOnly);
                        InsertSingleElementIntoXMLTextWriter(xmlTextWriter, ElementNames.XmlNodeNonStaffingFields);

                        xmlTextWriter.WriteEndElement();
                        xmlTextWriter.WriteEndDocument();
                        xmlTextWriter.Flush();
                        xmlTextWriter.Close();
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }

                infoPathFormData = memoryStream.GetBuffer();
            }
            // Filter out null characters
            return infoPathFormData.Where(b => b != '\0').ToArray();
        }
    }
}
